<template>
  <div class="app">
    <div class="top-wrap">
      <img class="banner" src="../../assets/image/banner/infoBanner.png" alt="">
      <div class="top-box">
        <div class="handle-bar">
          <div v-show="!isEdit && isPublic === false" class=""></div>
          <div v-show="!isEdit && isPublic === false" class="edit-item" @click="logOut">注销</div>
          <div v-show="isEdit" class="edit-item" @click="editCancel">取消</div>
          <div v-show="isEdit" class="edit-item" @click="editConfirm">保存</div>
        </div>
        <img class="avatar" :src="form.headPicUrl" alt="">
        <span v-show="!isEdit" class="edit-txt" @click="editClick">编辑资料</span>
      </div>
    </div>

    <div class="info-card">
      <div class="item-wrap">
        <div class="input-title"><span>姓名</span></div>
        <div class="input-wrap">
          <input
            v-show="isEdit"
            v-model="form.name"
            class="input-content"
            type="text"
            data-name="name"
            maxlength="10"
            placeholder="请输入姓名"
            @input="userInput"
          >
          <span v-show="!isEdit" class="input-content input-gray">{{ form.name }}</span>
        </div>
      </div>
      <div class="item-wrap">
        <div class="input-title"><span>手机号码</span></div>
        <div class="input-wrap">
          <input
            v-show="isEdit"
            v-model="form.phone"
            class="input-content"
            data-name="phone"
            placeholder="请输入手机号码"
            maxlength="11"
            pattern="[0-9]*"
            type="tel"
            @input="userInput"
          >
          <span v-show="!isEdit" class="input-content input-gray">{{ form.phone }}</span>
        </div>
      </div>
      <SjCode v-if="isEdit" :can-get-code="canGetCode" :tel="form.phone" @codeInput="codeInput"></SjCode>
      <div class="item-wrap">
        <div class="input-title"><span>身份证号</span></div>
        <div class="input-wrap">
          <input
            v-show="isEdit"
            v-model="form.idCardNumber"
            class="input-content"
            type="text"
            maxlength="18"
            data-name="idCardNumber"
            placeholder="请输入身份证号"
            @input="userInput"
          >
          <div v-show="!isEdit" class="input-content input-gray">{{ form.idCardNumber }}</div>
        </div>
      </div>
    </div>

    <div class="help-card">
      <span>员工认证</span>
      <span v-show="applyStatus === -1" style="color: #267eff" @click="pickVisible = true">进行认证</span>
      <span v-show="applyStatus === 0" style="color: #FF9E3D">审核中</span>
      <span v-show="applyStatus === 2">
        <span style="color: #c6c9cc">已拒绝&nbsp;&nbsp;&nbsp;</span>
        <span style="color: #267eff" @click="pickVisible = true">再次认证</span>
      </span>
      <!-- <img src="../../assets/image/icon/help-icon.png" alt=""> -->
    </div>
    <SjPicker
      :title="'请选择部门'"
      :show-picker="pickVisible"
      :key-name="'name'"
      :columns="dpList"
      @cancel="applyCancel"
      @selected="applySelected"
    ></SjPicker>

    <router-link :to="{path: '/visitorHelp'}">
      <div class="explain">使用说明</div>
    </router-link>
  </div>
</template>

<script>
import vant from 'vant'
import SjCode from '@/components/SjCode/index.vue'
import commonUtils from '@/utils/common.js'
import { userGetAPI, userUpdateAPI, departmentPageAPI, staffApplyStatusAPI, staffApplyAPI } from '@/axios/api/visitor'
import SjPicker from '@/components/SjPicker/index.vue'
import { Dialog } from 'vant'
export default {
  name: 'VisitorInfo',
  components: {
    SjCode,
    SjPicker
  },
  data() {
    return {
      unitId: '',
      isPublic: null,
      isCountDown: false,
      countNum: '',
      isEdit: false,
      form: {
        headPicUrl: '',
        name: '',
        phone: '',
        idCardNumber: '',
        code: ''
      },
      copyForm: {
        name: '',
        phone: '',
        idCardNumber: ''
      },
      applyStatus: '', // -1(未申请)、0(申请中)、1(申请中)、2(已拒绝)
      pickVisible: false,
      dpList: []
    }
  },
  computed: {
    canGetCode() {
      if ((/^1[3456789]\d{9}$/.test(this.form.phone))) {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    document.title = '个人信息'
    this.unitId = localStorage.getItem('visitorH5_unitId')
    this.isPublic = this.$store.getters.isPublic
    this.getUserInfo()
    this.getStaffApplyStatus()
    this.getDpList()
  },
  methods: {
    userInput(e) {
      this.form[e.target.dataset.name] = e.target.value.replace(/\s*/g, '')
    },
    codeInput(e) {
      this.form.code = e.value
    },
    // 点击编辑
    editClick() {
      this.isEdit = true
      this.form.phone = this.copyForm.phone
      this.form.idCardNumber = this.copyForm.idCardNumber
    },
    // 保存编辑
    editConfirm() {
      if (commonUtils.click_busy()) return
      if (!this.form.name.length) return vant.Toast('姓名不能为空')
      if (!(/^1[3456789]\d{9}$/.test(this.form.phone))) return vant.Toast('输入的手机号码格式有误，请重新输入')
      if (this.form.phone !== this.copyForm.phone && !this.form.code.length) return vant.Toast('验证码不能为空')
      const ID_reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      if (!ID_reg.test(this.form.idCardNumber)) return vant.Toast('身份证格式有误，请重新输入')
      userUpdateAPI(this.form).then(res => {
        vant.Toast('保存成功')
        this.isEdit = false
        this.getUserInfo()
      }).catch(res => {
        vant.Toast(res.data.detail || '保存失败')
      })
    },
    // 取消编辑
    editCancel() {
      this.isEdit = false
      this.form.name = this.copyForm.name
      this.form.phone = this.copyForm.phone.replace(/^(\d{3})\d*(\d{4})$/, '$1****$2')
      this.form.idCardNumber = this.copyForm.idCardNumber.replace(/(\d{6})\d*([0-9a-zA-Z]{4})/, '$1********$2')
      this.form.code = ''
    },
    // 获取最新信息
    getUserInfo() {
      userGetAPI().then(res => {
        this.copyForm = Object.assign({}, res)
        res.phone = res.phone.replace(/^(\d{3})\d*(\d{4})$/, '$1****$2')
        res.idCardNumber = res.idCardNumber.replace(/(\d{6})\d*([0-9a-zA-Z]{4})/, '$1********$2')
        this.form = Object.assign({
          headPicUrl: '',
          name: '',
          phone: '',
          idCardNumber: '',
          code: ''
        }, res)
        if (!this.form.headPicUrl) {
          this.form.headPicUrl = require('../../assets/image/default/avatar.png')
        }
      }).catch(res => {
        vant.Toast('获取个人信息失败')
      })
    },
    // 获取部门列表
    getDpList() {
      departmentPageAPI({ unitId: this.unitId }).then(res => {
        const list = []
        res.map(v => {
          list.push({
            name: v.name,
            id: v.id
          })
        })
        this.dpList = list
      }).catch(res => { })
    },
    // 获取 认证员工状态
    getStaffApplyStatus() {
      const userInfo = JSON.parse(localStorage.getItem('visitorH5_userInfo'))
      staffApplyStatusAPI({
        userId: userInfo.userId,
        unitId: this.unitId
      }).then(res => {
        // -1(未申请)、0(申请中)、1(申请中)、2(已拒绝)
        if (res) {
          this.applyStatus = res.status
        } else {
          this.applyStatus = -1
        }
      }).catch(res => { })
    },
    // 取消申请
    applyCancel(e) {
      this.pickVisible = false
    },
    // 确认申请
    applySelected(e) {
      if (e && e.value) {
        Dialog.confirm({
          message: `确认选择${e.value.name}吗`
        })
          .then(() => {
            this.staffApply(e.value)
          })
          .catch(() => {
            this.pickVisible = false
          })
      }
    },
    // 调用 申请接口
    staffApply(value) {
      const params = {
        name: this.copyForm.name, // 申请人姓名
        phone: this.copyForm.phone, // 申请人电话
        depId: value.id,
        unitId: this.unitId
      }
      staffApplyAPI(params).then(res => {
        this.pickVisible = false
        vant.Toast.success('提交成功')
      }).catch(res => { })
    },
    // H5 退出登录
    logOut() {
      Dialog.confirm({
        title: '提示',
        message: '确认注销吗？'
      }).then(() => {
        localStorage.removeItem('visitorH5_token')
        localStorage.removeItem('visitorH5_userInfo')
        window.location.href = this.getUnitInfo().H5Url
      }).catch(() => {
        // on cancel
      })
    }
  }
}
</script>

<style lang='scss' scoped>
@mixin w-h($width, $height) {
  width: $width;
  height: $height;
}
@mixin flex-config($justify-content, $align-items) {
  display: flex;
  justify-content: $justify-content;
  align-items: $align-items;
}
@mixin font-s-w-c($size, $weight, $color) {
  font-size: $size;
  font-weight: $weight;
  color: $color;
}

.top-wrap {
  position: relative;
  @include w-h(100vw, 45.33vw);

  .banner {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    display: block;
  }

  .top-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    .handle-bar {
      @include w-h(100%, 50px);
      @include flex-config(space-between, flex-start);

      .edit-item {
        @include w-h(58px, 50px);
        @include font-s-w-c(14px, 500, #fff);
        line-height: 50px;
        text-align: center;
      }
    }
    .avatar {
      @include w-h(58px, 58px);
      margin-top: 10px;
      border-radius: 50%;
    }
    .edit-txt {
      @include w-h(56px, 20px);
      @include font-s-w-c(14px, 500, #fff);
      margin-top: 8px;
      line-height: 20px;
      text-align: center;
    }
  }
}

.info-card {
  position: relative;
  z-index: 1;
  margin: 0 15px;
  padding: 8px 15px 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0px 3px 6px rgba(38, 126, 255, 0.16);

  .item-wrap {
    position: relative;
    height: 46px;
    padding: 16px 0 8px;
    border-bottom: 1px solid #f1f2f3;
    @include flex-config(flex-start, center);
    .input-title {
      min-width: 92px;
      @include w-h(92px, 21px);

      span {
        line-height: 21px;
        @include font-s-w-c(15px, 500, #707070);
      }
    }
    .input-wrap {
      width: 100%;
      .input-content {
        @include w-h(100%, 21px);
        @include font-s-w-c(15px, 500, black);
        line-height: 21px;
      }
      .input-gray {
        color: #c6c9cc !important;
      }
    }
  }
}

.help-card {
  margin: 12px 15px 0;
  padding: 24px 15px;
  height: 69px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0px 3px 6px rgba(38, 126, 255, 0.16);
  @include flex-config(space-between, center);

  span {
    height: 21px;
    line-height: 21px;
    @include font-s-w-c(15px, 500, #707070);
  }

  img {
    margin-right: 12px;
    @include w-h(12px, 12px);
  }
}

.explain {
  padding: 15px;
  height: 21px;
  line-height: 21px;
  @include font-s-w-c(13px, 400, #267eff);
  text-align: right;
}
</style>
